package com.sanjiahantang.youjiarole.module.me.quotation.views.impl;

import android.content.Intent;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiarole.R;
import com.sanjiahantang.youjiarole.base.BaseMvpActivity;
import com.sanjiahantang.youjiarole.config.ConfigValue;
import com.sanjiahantang.youjiarole.config.SPConfig;
import com.sanjiahantang.youjiarole.module.common.views.impl.WebActivity;
import com.sanjiahantang.youjiarole.module.me.quotation.beans.ContractRequestBean;
import com.sanjiahantang.youjiarole.module.me.quotation.beans.QuotationResponseBean;
import com.sanjiahantang.youjiarole.module.me.quotation.preseneters.QuotationPresenter;
import com.sanjiahantang.youjiarole.module.me.quotation.views.QuotationView;
import com.sanjiahantang.youjiarole.module.me.require.beans.RequireDetailInitResponseBean;
import com.sanjiahantang.youjiarole.utils.SPUtils;

import java.util.HashMap;

/**
 * Created by zy on 2017/10/31.
 */

public class QuotationActivity extends BaseMvpActivity<QuotationView, QuotationPresenter> implements QuotationView, View.OnClickListener {

    private int id;
    private int num, stock;
    private float price;
    private TextView txtPrice, txtTotal, txtSubmit, txtTag, txtPriceTag,number_add,txtContract;
    private EditText txtNum;
    private QuotationResponseBean.Data data;
    private RequireDetailInitResponseBean.Data requireBean;
    private CheckBox cbContract, cbFree;
    private String customerPhone;
    private String userCode;
    private String signer1, contractCode;
    private int pcId;
    private boolean canCheck = false;
    private View vContract, vFree, panelPrice,number_sub, panelSendPrice;
    private String designerRolePhone;//分包人手机号
    private String designerRole;
    private String designerRoleName;
    private final String STR_CONTRACT_SIGNED = "合同已签署，请推送给客户";
    private final String STR_CONTRACT = "优家库设计合同";

    @Override
    public void showProgress() {
        super.showProgress($this);
    }

    @Override
    public QuotationPresenter initPresenter() {
        return new QuotationPresenter();
    }

    @Override
    public void initView() {
        id = getIntent().getIntExtra(KEY_ID, 0);

        requireBean = (RequireDetailInitResponseBean.Data) getIntent().getSerializableExtra(KEY_PARAM);
        customerPhone = requireBean.getPhone();
        userCode = requireBean.getUserCode();
        if (1 == requireBean.getIsSubcontract()){
            designerRolePhone = requireBean.getDesignRoleId();
            designerRole = "0,1,3";
            designerRoleName = requireBean.getDesignRoleName();
        }else{
            designerRolePhone = SPUtils.get($this,SPConfig.PHONE,"").toString();
            designerRole = SPUtils.get($this, SPConfig.ROLE_ID, "").toString();
            designerRoleName = SPUtils.get($this, SPConfig.USERNAME, "").toString();
        }

        setContentView(R.layout.activity_quotation);
        cbContract = (CheckBox) findViewById(R.id.cbContract);
        cbFree = (CheckBox) findViewById(R.id.cbFree);
        txtSubmit = (TextView) findViewById(R.id.txtSubmit);
        txtSubmit.setOnClickListener(this);
        TextView title = (TextView) findViewById(R.id.title);
        title.setText("设计报价");
        findViewById(R.id.fl_Left).setOnClickListener(this);
//        TextView txtState = (TextView) findViewById(R.id.txtCreateTime);
//        txtState.setText("待付款");
//        ImageView ivState = (ImageView) findViewById(R.id.ivState);
//        ivState.setImageResource(R.drawable.i_unpay_head);

        txtPrice = (TextView) findViewById(R.id.txtPrice);
        txtNum = (EditText) findViewById(R.id.txtNum);
        txtNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                int value = 0;
                try {
                    value = Integer.valueOf(s.toString());
                }catch (Exception e){
                    value = 0;
                }
                num = value;

                txtTotal.setText(String.valueOf(price * value));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        txtTotal = (TextView) findViewById(R.id.txtTotal);
        txtTag = (TextView) findViewById(R.id.txtTag);
        txtPriceTag = (TextView) findViewById(R.id.txtPriceTag);

        num = 1;

        number_sub = findViewById(R.id.number_sub);
        number_sub.setOnClickListener(this);
        number_add = (TextView) findViewById(R.id.number_add);
        number_add.setOnClickListener(this);

        panelPrice = findViewById(R.id.panelPrice);
        vContract = findViewById(R.id.vContract);
        txtContract = (TextView) findViewById(R.id.txtContract);
        txtContract.setText(STR_CONTRACT);
        panelSendPrice = findViewById(R.id.panelSendPrice);

        vContract.setOnClickListener(this);
        cbContract.setOnClickListener(this);
        vFree = findViewById(R.id.vFree);
        vFree.setOnClickListener(this);
        cbFree.setOnClickListener(this);
    }

    @Override
    public void initData() {
        presenter.loadOrder($this, id, new OnLoadListener() {
            @Override
            public void onLoad(Object content) {
                data = (QuotationResponseBean.Data) content;
                price = Float.valueOf(data.getResultPrice());
                txtPrice.setText(String.valueOf(price));
                stock = data.getStockCount();
                txtTotal.setText(String.valueOf(price * num));
            }
        });
    }

    @Override
    public void onClick(View view) {
        resetCount();
        switch (view.getId()) {
            case R.id.txtSubmit:
                if (data != null) {
                    if (cbContract.isChecked()) {
                        ContractRequestBean postData = new ContractRequestBean();
                        postData.setToken(ConfigValue.DATA_KEY);
                        postData.setRequireId(requireBean.getId());
                        postData.setServicePrice(String.valueOf(price));
                        postData.setServiceNum(num);
                        postData.setServiceCount(String.valueOf(price * num));
                        postData.setSkuId(data.getSkuId());
                        postData.setRolePhone(SPUtils.get($this, SPConfig.PHONE, "").toString());
                        postData.setPhone(requireBean.getPhone());
                        postData.setRoleId(SPUtils.get($this, SPConfig.ROLE_ID, "").toString());
                        postData.setMgiId(data.getMgiId());
                        postData.setPcId(pcId);
                        postData.setContractCode(contractCode);
                        postData.setDesignName(SPUtils.get($this, SPConfig.USERNAME, "").toString());
                        postData.setCustomerName(requireBean.getUserName());
                        postData.setSigner1(signer1);
                        postData.setSigner2(requireBean.getUserCode());
                        postData.setIsDesignFree(0);
                        if (data.getPspId() > 0) {
                            postData.setPspId(String.valueOf(data.getPspId()));
                        }
                        presenter.saveProjectServicePriceDesignPhone(
                                $this,
                                postData);
                    } else if (cbFree.isChecked()) {
                        ContractRequestBean postData = new ContractRequestBean();
                        postData.setToken(ConfigValue.DATA_KEY);
                        postData.setRequireId(requireBean.getId());
                        postData.setRolePhone(designerRolePhone);
                        postData.setPhone(requireBean.getPhone());
                        postData.setRoleId(designerRole);
                        postData.setPcId(pcId);
                        postData.setDesignName(designerRoleName);
                        postData.setCustomerName(requireBean.getUserName());
                        postData.setSigner1(signer1);
                        postData.setSigner2(requireBean.getUserCode());
                        postData.setIsDesignFree(1);
                        if (data.getPspId() > 0) {
                            postData.setPspId(String.valueOf(data.getPspId()));
                        }
                        presenter.saveProjectServicePriceDesignPhone(
                                $this,
                                postData);
                    } else {
                        Utils.showToast($this, "请签署优家库设计合同");
                        signContract();
                    }
                }

                break;
            case R.id.fl_Left:
                finish();
                break;
            case R.id.number_add:
                if (num < stock) {
                    num++;
                    txtNum.setText(String.valueOf(num));
                    txtTotal.setText(String.valueOf(price * num));
                }
                break;
            case R.id.number_sub:
                if (num > 1) {
                    num--;
                    txtNum.setText(String.valueOf(num));
                    txtTotal.setText(String.valueOf(price * num));
                }
                break;
            case R.id.vContract:
            case R.id.cbContract:
                if (data != null && !canCheck) {
                    signContract();
                } else if (data != null) {
                    cbContract.setChecked(true);
                    txtContract.setText(STR_CONTRACT_SIGNED);
                    changeUIFromFreeToContract();
                } else {
                    Utils.showToast($this, " ");
                }

                break;
            case R.id.vFree:
            case R.id.cbFree:
                cbContract.setChecked(false);
                changeUIFromContractToFree();
                break;
        }
    }

    private void resetCount(){
        if (num > stock) {
            num = stock;
        }
        if (num < 1) {
            num = 1;
        }
        txtNum.setText(String.valueOf(num));
        txtTotal.setText(String.valueOf(price * num));
    }

    private void signContract() {
        cbContract.setChecked(false);
        presenter.contractSignForDesign($this,
                customerPhone,
                designerRolePhone,
                userCode,
                new OnLoadListener() {
                    @Override
                    public void onLoad(Object content) {
                        if (content != null && content instanceof HashMap) {
                            HashMap<String, Object> map = (HashMap<String, Object>) content;
                            if (map.containsKey("signer1")) {
                                signer1 = (String) map.get("signer1");
                            }

                            if (map.containsKey("contractCode")) {
                                contractCode = (String) map.get("contractCode");
                            }

                            if (map.containsKey("pcId")) {
                                pcId = (int) map.get("pcId");
                            }

                            if (!TextUtils.isEmpty(signer1) && !TextUtils.isEmpty(contractCode)) {
                                String param = "contractCode=" + contractCode + "&signer=" + signer1;
                                startActivityForResult(new Intent($this, WebActivity.class)
                                        .putExtra(KEY_TYPE, WEB_TYPE_CONTRACT)
                                        .putExtra(KEY_PARAM, param), 1);
                            } else {
                                Utils.showToast($this, "创建合同失败");
                            }

                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            canCheck = true;
            cbContract.setChecked(true);
            txtContract.setText(STR_CONTRACT_SIGNED);
            changeUIFromFreeToContract();
        }
    }

    private void changeUIFromContractToFree() {
        panelPrice.setBackgroundResource(R.color.gray_e8);
//        vContract.setBackgroundResource(R.color.gray_e8);
        number_add.setEnabled(false);
        number_sub.setEnabled(false);
        cbContract.setChecked(false);
        panelSendPrice.setVisibility(View.INVISIBLE);
        txtSubmit.setText("提交");
        txtTag.setTextColor(Color.GRAY);
        txtNum.setTextColor(Color.GRAY);
        txtPriceTag.setTextColor(Color.GRAY);
        txtPrice.setTextColor(Color.GRAY);
        number_add.setTextColor(Color.GRAY);
//        vFree.setBackgroundResource(R.color.white);
        cbFree.setChecked(true);
    }

    private void changeUIFromFreeToContract() {
        panelPrice.setBackgroundResource(R.color.white);
//        vContract.setBackgroundResource(R.color.white);
        number_add.setEnabled(true);
        number_sub.setEnabled(true);
        panelSendPrice.setVisibility(View.VISIBLE);
        txtSubmit.setText("推送给客户");
        txtTag.setTextColor(Color.BLACK);
        txtNum.setTextColor(Color.BLACK);
        txtPriceTag.setTextColor(Color.BLACK);
        txtPrice.setTextColor(Color.BLACK);
        number_add.setTextColor(COLOR_PRIMARY);
//        vFree.setBackgroundResource(R.color.gray_e8);
        cbFree.setChecked(false);
    }
}
